import { useAsync } from "utils/use-async";
import { Project } from "types/project";
import { useCallback, useEffect } from "react";
import { cleanObject } from "utils/index";
import { useHttp } from "utils/http";
import { QueryKey, useMutation, useQuery } from "react-query";
import {
  useAddConfig,
  useDeleteConfig,
  useEditConfig,
} from "utils/use-optimistic-options";

// 请求数据 并用useQuery命名为projects，且随param变化重新触发
export const useProjects = (param?: Partial<Project>) => {
  const client = useHttp();
  return useQuery<Project[]>(["projects", param], () =>
    client("projects", { data: param })
  );
};

// PATCH修改 projects数据 用useMutation添加给数据请求添加loading success ...等状态
export const useEditProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Project>) =>
      client(`projects/${params.id}`, { data: params, method: "PATCH" }),
    useEditConfig(queryKey) //请求成功，自动刷新列表
  );
};

// POST新增 projects数据 用useMutation添加给数据请求添加loading success ...等状态
export const useAddProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Project>) =>
      client(`projects`, { data: params, method: "POST" }),
    useAddConfig(queryKey)
  );
};

// 删除
export const useDeleteProject = (queryKey: QueryKey) => {
  const client = useHttp();

  return useMutation(
    (
      { id }: { id: number } //target 的 id
    ) =>
      client(`projects/${id}`, {
        method: "DELETE",
      }),
    useDeleteConfig(queryKey)
  );
};

// 更具id请求数据 并用useQuery命名为projects，且随id变化重新触发
export const useProject = (id?: number) => {
  const client = useHttp();
  return useQuery<Project>(
    ["project", { id }],
    () => client(`projects/${id}`),
    { enabled: Boolean(id) } //当id有值的时候，才会触发useProject
  );
};
